package com.lovo.movie.service.impl;

import com.lovo.dto.OrderDto;
import com.lovo.movie.dao.MoiveDAO;
import com.lovo.movie.entity.MoiveEntity;
import com.lovo.movie.service.IOrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
@Service
public class OrderMQ {
    @Resource
    private MoiveDAO dao;
//    @Autowired
    @Resource
    private IOrderService orderService;



   @RabbitListener(queues = {"lcq_point","deadQueue"})
    public void getOrder(OrderDto orderDto, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag){


       try {
           String orderNum = orderDto.getOrderNum();
           String movieName = orderDto.getMovieName();
           MoiveEntity movie = dao.findByMovieName(movieName);
           if (movie.getMovieNum()<orderDto.getMovieNum()){
               System.out.println("票不够");
               //远程调用
               orderService.update2(new OrderDto(orderNum));
               channel.basicAck(tag,false);
               return;
           }
           movie.setMovieNum(movie.getMovieNum()-orderDto.getMovieNum());
           dao.save(movie);
           //远程调用
           System.out.println(orderNum);
           orderService.update3(new OrderDto(orderNum));
           System.out.println("成功");
           channel.basicAck(tag,false);






           //tag-队列中数据的标记，flase-非批量确认
//           channel.basicAck(tag,false);
           //不确认，false不批量处理，true,不消费，继续保留在队列中
           //第三个被拒绝的是否重新入队列
//           channel.basicNack(tag,false,true);

       } catch (Exception e) {
           e.printStackTrace();
           try {
               channel.basicNack(tag,false,true);
           } catch (IOException ex) {
               ex.printStackTrace();
           }
       }

   }
}
